"""
星级评分组件
提供可交互的星级评分UI
"""

import tkinter as tk
from tkinter import ttk
from core.utils.logger import debug
from ui.styles.theme import Theme


class StarRating(ttk.Frame):
    """星级评分组件"""
    
    def __init__(self, parent, rating=0, editable=True, on_change=None, size=16):
        """
        初始化星级评分组件
        
        Args:
            parent: 父组件
            rating: 初始评分 (0-5)
            editable: 是否可编辑
            on_change: 评分变化回调函数
            size: 星星大小
        """
        super().__init__(parent)
        
        self.rating = rating
        self.editable = editable
        self.on_change = on_change
        self.size = size
        
        self.stars = []
        self._create_stars()
        self._update_display()
    
    def _create_stars(self):
        """创建星星标签"""
        # 获取主题颜色
        inactive_color = Theme.get_color('fg_tertiary')
        active_color = '#FFD700'  # 金色保持明亮
        
        for i in range(5):
            star = tk.Label(
                self, 
                text='☆', 
                font=('Arial', self.size),
                foreground=inactive_color,
                cursor='hand2' if self.editable else 'arrow'
            )
            star.pack(side='left', padx=2)
            
            if self.editable:
                star.bind('<Button-1>', lambda e, idx=i: self._click(idx))
                star.bind('<Enter>', lambda e, idx=i: self._hover(idx))
                star.bind('<Leave>', lambda e: self._update_display())
            
            self.stars.append(star)
    
    def _click(self, index):
        """点击星星"""
        if self.editable:
            self.rating = index + 1
            if self.on_change:
                self.on_change(self.rating)
            self._update_display()
            debug(f"用户选择评分: {self.rating}星")
    
    def _hover(self, index):
        """鼠标悬停"""
        inactive_color = Theme.get_color('fg_tertiary')
        active_color = '#FFD700'  # 金色保持明亮
        
        if self.editable:
            for i, star in enumerate(self.stars):
                if i <= index:
                    star.config(text='★', foreground=active_color)
                else:
                    star.config(text='☆', foreground=inactive_color)
    
    def _update_display(self):
        """更新显示"""
        inactive_color = Theme.get_color('fg_tertiary')
        active_color = '#FFD700'  # 金色保持明亮
        
        for i, star in enumerate(self.stars):
            if i < self.rating:
                star.config(text='★', foreground=active_color)
            else:
                star.config(text='☆', foreground=inactive_color)
    
    def set_rating(self, rating):
        """设置评分"""
        if 0 <= rating <= 5:
            self.rating = rating
            self._update_display()
    
    def get_rating(self):
        """获取当前评分"""
        return self.rating
    
    def get_rating_display(self):
        """获取评分的星号显示"""
        return "★" * self.rating + "☆" * (5 - self.rating)
    
    def get_rating_text(self):
        """获取评分的文字描述"""
        rating_texts = {
            0: "未评分",
            1: "很差",
            2: "较差", 
            3: "一般",
            4: "较好",
            5: "很好"
        }
        return rating_texts.get(self.rating, "未知")


class StarRatingDisplay(ttk.Frame):
    """只读星级显示组件（用于显示平均分等）"""
    
    def __init__(self, parent, rating=0, size=14, show_text=True):
        """
        初始化只读星级显示组件
        
        Args:
            parent: 父组件
            rating: 评分 (0-5，支持小数)
            size: 星星大小
            show_text: 是否显示文字
        """
        super().__init__(parent)
        
        self.rating = rating
        self.size = size
        self.show_text = show_text
        
        self._create_display()
    
    def _create_display(self):
        """创建显示组件"""
        # 获取主题颜色
        inactive_color = Theme.get_color('fg_tertiary')
        active_color = '#FFD700'  # 金色保持明亮
        text_color = Theme.get_color('fg_secondary')
        
        # 星星显示
        stars_frame = ttk.Frame(self)
        stars_frame.pack(side='left')
        
        full_stars = int(self.rating)
        has_half = self.rating - full_stars >= 0.5
        
        for i in range(5):
            if i < full_stars:
                star = tk.Label(stars_frame, text='★', font=('Arial', self.size), foreground=active_color)
            elif i == full_stars and has_half:
                star = tk.Label(stars_frame, text='★', font=('Arial', self.size), foreground=active_color)
            else:
                star = tk.Label(stars_frame, text='☆', font=('Arial', self.size), foreground=inactive_color)
            
            star.pack(side='left', padx=1)
        
        # 评分文字
        if self.show_text:
            rating_text = f"{self.rating:.1f}" if isinstance(self.rating, float) else str(self.rating)
            text_label = tk.Label(self, text=rating_text, font=('Arial', self.size-2), foreground=text_color)
            text_label.pack(side='left', padx=(5, 0))
    
    def update_rating(self, rating):
        """更新评分显示"""
        self.rating = rating
        # 清除现有组件
        for widget in self.winfo_children():
            widget.destroy()
        # 重新创建
        self._create_display()
